package com.wlstock.funi.runnable;

import java.io.IOException;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.wlstock.funi.R;
import com.wlstock.funi.app.FundApplication;
import com.wlstock.funi.app.FundAsyTask;
import com.wlstock.funi.app.FundAsyTask.TaskLitener;
import com.wlstock.funi.model.PendTradeModel;
import com.wlstock.funi.utils.IOUtils;
import com.wlstock.funi.utils.NotiIdGenerator;
import com.wlstock.funi.utils.NotiUtils;
import com.wlstock.funi.utils.ToastUtils;

public class PendTradeList {
	
	public enum RESULT_CODE{
		RESULT_EMPTY,
		RESULT_ERROR,
		RESULT_REDIRECT,
		RESULT_DATAS
	}
	
	
	public void request(final onResultListener listener){
		if (!FundApplication.isLogSuccess) {
			NotiUtils.showSimpleNoti(FundApplication.getInstance(), NotiIdGenerator.ID_LOG_OUTDATE, "登陆失效，请重新登陆", "无法获取最新价格", R.drawable.ic_exception);
			ToastUtils.showMiddleMsg(FundApplication.getInstance(), "尚未登录，无法获取最新价格");
			return;
		}
		
		if (listener == null) {
			return;
		}
		
		StringBuffer sb = new StringBuffer();
		sb.append("https://etrade.cs.ecitic.com/ymtrade/trade/stockAction.do?method=getCancel");
		FundAsyTask<String, Void, Void> task = new FundAsyTask<String, Void, Void>();
		task.backListener = new TaskLitener<String, Void>() {

			@Override
			public Void doInBackground(String... params) {
				HttpClient client = new DefaultHttpClient();
				
				HttpGet hGet = new HttpGet(params[0]);
				hGet.addHeader("Accept","*/*");
				hGet.addHeader("Accept-Encoding","gzip, deflate");
				hGet.addHeader("Accept-Language","zh-CN,zh;q=0.8,en;q=0.6");
				hGet.addHeader("Content-Length","0");
				hGet.addHeader("Content-Type","text/plain;charset=UTF-8");
				hGet.addHeader("Host","etrade.cs.ecitic.com");
				hGet.addHeader("Origin","https://etrade.cs.ecitic.com");
				hGet.addHeader("Cookie",FundApplication.cookie);
				hGet.addHeader("Referer","https://etrade.cs.ecitic.com/ymtrade/stock/cancel.jsp");
				hGet.addHeader("User-Agent","Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.86 Safari/537.36");
				hGet.addHeader("X-Requested-With","XMLHttpRequest");
				
				try {
					HttpResponse response = client.execute(hGet);
					
					if (response.getStatusLine().getStatusCode() == 200) {
						String result = IOUtils.is2Str(response.getEntity().getContent());
						
						Pattern compile = Pattern.compile("记录个数：[0-9]*");
						Matcher matcher = compile.matcher(result);
						String totalCount = "";
						while(matcher.find()){
							 totalCount = result.substring(matcher.start()+5, matcher.end());
						}
						if (!totalCount.isEmpty() && totalCount.equals("0")) {
							//判断是网络错误还是真的记录为0
							if (result.contains("网络错误")) {
								listener.onResult(RESULT_CODE.RESULT_ERROR, null);
							}else if (result.contains("没有记录")) {
								listener.onResult(RESULT_CODE.RESULT_EMPTY, null);
							}
						}else if (!totalCount.isEmpty()) {
							ArrayList<PendTradeModel> pendList = new ArrayList<PendTradeModel>();
							//总数量不为0
							Document doc = Jsoup.parse(result);
							Elements selItems = doc.select("[align=\"right\"]");
							//需要减去最后的一个
							if (selItems.size()-1 == Integer.valueOf(totalCount)) {
								for (Element oddRedItem : selItems) {
									Elements childItems = oddRedItem.children();
									//正确的item
									if (childItems.size() == 19) {
										PendTradeModel model = new PendTradeModel(childItems);
										pendList.add(model);
									}
								}
								listener.onResult(RESULT_CODE.RESULT_DATAS, pendList);
							}else{
								//数量有误，仍然判定异常
								listener.onResult(RESULT_CODE.RESULT_ERROR, null);
							}
						}else {
							//网络异常，可能去到重定向页面
							listener.onResult(RESULT_CODE.RESULT_REDIRECT, null);
						}
					}else {
						//网络异常，可能服务器拒绝访问
						listener.onResult(RESULT_CODE.RESULT_REDIRECT, null);
					}
					
				} catch (ClientProtocolException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} finally{
					client.getConnectionManager().shutdown();
				}
				return null;
			}
		};
		
		task.execute(sb.toString());
		
	}

	
	public interface onResultListener{
		public void onResult(RESULT_CODE code, ArrayList<PendTradeModel> list);
	}
	
	
	
}
